package dao;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import dto.CarteDTO;
import dto.EmployeeDTO;
import entities.Carte;

@Stateless
public class CarteDAO implements CarteDAORemote {

	@PersistenceContext
	EntityManager em;

	public CarteDAO() {

	}

	@Override
	public void add(CarteDTO carteDTO) {
		try {
			Carte c = new Carte();
			c.setNume(carteDTO.getNume());
			c.setAnul(carteDTO.getAnul());
			c.setAutor(carteDTO.getAutor());
			c.setData_retur(carteDTO.getData_retur());
			c.setImprumutata_de(carteDTO.getImprumutata_de());
			c.setStatus(carteDTO.getStatus());

			em.persist(c);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<CarteDTO> findAllBooks() {
		/*
		TypedQuery<Carte> query = em.createQuery("SELECT e FROM Carte e",
				Carte.class);
		*/
		Query query = em.createNamedQuery("getToateCartile");
		List<Carte> carte = query.getResultList();
		List<CarteDTO> result = new ArrayList<CarteDTO>();
		for (int i = 0; i < carte.size(); i++) {
			CarteDTO c = new CarteDTO();
			c.setNume(carte.get(i).getNume());
			c.setAutor(carte.get(i).getAutor());
			c.setAnul(carte.get(i).getAnul());
			c.setData_retur(carte.get(i).getData_retur());
			c.setImprumutata_de(carte.get(i).getImprumutata_de());
			c.setStatus(carte.get(i).getStatus());
			c.setId(carte.get(i).getId());
			result.add(c);
		}
		return result;
	}

	@Override
	public void update(int upd, String ce, String lace) {
		if (ce.equals("Nume")) {
			TypedQuery<Carte> query = em.createQuery(
					"UPDATE Carte SET nume = '" + lace + "' WHERE id  ='" + upd
							+ "'", Carte.class);
			query.executeUpdate();
		}
		if (ce.equals("Autor")) {
			TypedQuery<Carte> query = em.createQuery(
					"UPDATE Carte SET autor = '" + lace + "' WHERE id  ='"
							+ upd + "'", Carte.class);
			query.executeUpdate();
		}
		if (ce.equals("Anul")) {
			TypedQuery<Carte> query = em.createQuery(
					"UPDATE Carte SET anul = '" + lace + "' WHERE id  ='" + upd
							+ "'", Carte.class);
			query.executeUpdate();
		}
		if (ce.equals("Status")) {
			TypedQuery<Carte> query = em.createQuery(
					"UPDATE Carte SET status = '" + lace + "' WHERE id  ='"
							+ upd + "'", Carte.class);
			query.executeUpdate();
		}
		if (ce.equals("Data retur")) {
			TypedQuery<Carte> query = em.createQuery(
					"UPDATE Carte SET data_retur = '" + lace + "' WHERE id  ='"
							+ upd + "'", Carte.class);
			query.executeUpdate();
		}
		if (ce.equals("Imprumutata de")) {
			TypedQuery<Carte> query = em.createQuery(
					"UPDATE Carte SET imprumutata_de = '" + lace
							+ "' WHERE id  ='" + upd + "'", Carte.class);
			query.executeUpdate();
		}
		// "UPDATE Bilet SET status = '"+1+"' WHERE id = '"+biletId+"'",

	}

	public String plus2Weeks(String d) {
		// format: yyyy-mm-dd
		String z = "";
		z = z + d.charAt(8) + d.charAt(9);
		String l = "";
		l = l + d.charAt(5) + d.charAt(6);
		String a = "";
		a = a + d.charAt(0) + d.charAt(1) + d.charAt(2) + d.charAt(3);
		int zi = Integer.parseInt(z);
		int lu = Integer.parseInt(l);
		int an = Integer.parseInt(a);
		if (lu == 2) {
			if (zi > 14) {
				zi = zi + 14 - 28;
				lu = lu + 1;
			} else
				zi = zi + 14;
		} else if (lu == 4 || lu == 6 || lu == 9 || lu == 11) {
			if (zi > 16) {
				zi = zi + 14 - 30;
				lu = lu + 1;
			} else
				zi = zi + 14;
		} else {
			if (zi > 17) {
				zi = zi + 14 - 31;
				lu = lu + 1;
			} else
				zi = zi + 14;
		}
		if (lu == 13) {
			lu = 1;
			an = an + 1;
		}
		// System.out.println("An: " + an + " Lu: " + lu + " Zi: " + zi);
		String re = String.valueOf(an);
		re = re + "-" + String.valueOf(lu) + "-" + String.valueOf(zi);
		return re;
	}

	@Override
	public void imprumutare(int id, EmployeeDTO eDTO) {
		Query query = em.createNamedQuery("getCarteByID");
		query.setParameter("idParam", id);
		CarteDTO carteDTO = new CarteDTO();
		List<Carte> l = query.getResultList();
		if (l != null && l.size() > 0) {
			carteDTO.setAnul(l.get(0).getAnul());
			carteDTO.setId(l.get(0).getId());
			carteDTO.setNume(l.get(0).getNume());
			carteDTO.setAutor(l.get(0).getAutor());
			carteDTO.setStatus(l.get(0).getStatus());
			carteDTO.setData_retur(l.get(0).getData_retur());
			carteDTO.setImprumutata_de(l.get(0).getImprumutata_de());

			if (carteDTO.getStatus().equals("Disponibil")) {
				DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				Date date = new Date();
				String a = dateFormat.format(date).toString();
				String datare = plus2Weeks(a);
				carteDTO.setData_retur(plus2Weeks(a));
				String nume_prenume = eDTO.getLastname();
				nume_prenume = nume_prenume + " " + eDTO.getFirstname();
				carteDTO.setImprumutata_de(nume_prenume);
				carteDTO.setStatus("Imprumutat");
				TypedQuery<Carte> query2 = em.createQuery(
						"UPDATE Carte SET imprumutata_de = '" + nume_prenume
								+ "' WHERE id  ='" + id + "'", Carte.class);
				query2.executeUpdate();
				query2 = em.createQuery("UPDATE Carte SET data_retur = '"
						+ datare + "' WHERE id  ='" + id + "'", Carte.class);
				query2.executeUpdate();
				String sts = "Imprumutat";
				query2 = em.createQuery("UPDATE Carte SET status = '" + sts
						+ "' WHERE id  ='" + id + "'", Carte.class);
				query2.executeUpdate();

			} else {
				String data = carteDTO.getData_retur();
				String datare = plus2Weeks(data);
				String nume_prenume = eDTO.getLastname();
				nume_prenume = nume_prenume + " " + eDTO.getFirstname();
				String pana = carteDTO.getImprumutata_de();
				pana = pana + " / " + nume_prenume;
				TypedQuery<Carte> query2 = em.createQuery(
						"UPDATE Carte SET imprumutata_de = '" + pana
								+ "' WHERE id  ='" + id + "'", Carte.class);
				query2.executeUpdate();
				query2 = em.createQuery("UPDATE Carte SET data_retur = '"
						+ datare + "' WHERE id  ='" + id + "'", Carte.class);
				query2.executeUpdate();
			}

		} else {
			System.out.println("Baj van imprumutare!!");
		}

	}

	@Override
	public void returnare(int id, EmployeeDTO e) {
		Query query = em.createNamedQuery("getCarteByID");
		query.setParameter("idParam", id);
		CarteDTO carteDTO = new CarteDTO();
		List<Carte> l = query.getResultList();
		if (l != null && l.size() > 0) {
			carteDTO.setAnul(l.get(0).getAnul());
			carteDTO.setId(l.get(0).getId());
			carteDTO.setNume(l.get(0).getNume());
			carteDTO.setAutor(l.get(0).getAutor());
			carteDTO.setStatus(l.get(0).getStatus());
			carteDTO.setData_retur(l.get(0).getData_retur());
			carteDTO.setImprumutata_de(l.get(0).getImprumutata_de());

			if (!carteDTO.getStatus().equals("Disponibil"))
				if (!carteDTO.getData_retur().equals("1000-01-01"))
					if (!carteDTO.getImprumutata_de().equals("-")) {
						String fn = e.getFirstname();
						String ln = e.getLastname();
						String fl = ln + " " + fn;
						String tot = fl + " / ";
						String ide = carteDTO.getImprumutata_de();
						if (!ide.equals(fl)) {
							String idde = ide.replace(tot, "");
							TypedQuery<Carte> query2 = em.createQuery(
									"UPDATE Carte SET imprumutata_de = '"
											+ idde + "' WHERE id  ='" + id
											+ "'", Carte.class);
							query2.executeUpdate();
						} else {
							String idd = "-";
							String sts = "Disponibil";
							String data = "1000-01-01";
							TypedQuery<Carte> query2 = em.createQuery(
									"UPDATE Carte SET imprumutata_de = '" + idd
											+ "' WHERE id  ='" + id + "'",
									Carte.class);
							query2.executeUpdate();
							query2 = em.createQuery(
									"UPDATE Carte SET status = '" + sts
											+ "' WHERE id  ='" + id + "'",
									Carte.class);
							query2.executeUpdate();
							query2 = em.createQuery(
									"UPDATE Carte SET data_retur = '" + data
											+ "' WHERE id  ='" + id + "'",
									Carte.class);
							query2.executeUpdate();
						}
					}
		} else {
			System.out.println("Baj van returnare!!");
		}

	}

	@Override
	public void del(CarteDTO carte) {
		int id = carte.getId();
		Carte c = new Carte();
		c = em.find(Carte.class, id);
		em.remove(c);
	}

	@Override
	public void update(CarteDTO c) {
		int id = c.getId();
		Carte carte = new Carte();
		carte = em.find(Carte.class, id);
		carte.setAnul(c.getAnul());
		carte.setAutor(c.getAutor());
		carte.setData_retur(c.getData_retur());
		carte.setImprumutata_de(c.getImprumutata_de());
		carte.setNume(c.getNume());
		carte.setStatus(c.getStatus());
	}
	
	public boolean isNumber(String s){
		try { 
	        Integer.parseInt(s); 
	    } catch(NumberFormatException e) { 
	        return false; 
	    }
	    return true;
	}

	@Override
	public List<CarteDTO> getCarteDupa(String dupa, String valoare) {
		if ("Titlu".equals(dupa)) {
			Query query = em.createNamedQuery("dupaTitlu");
			query.setParameter("name_Param", valoare);
			List<Carte> carti = query.getResultList();
			List<CarteDTO> car = new ArrayList<CarteDTO>();// = new

			for (int i = 0; i < carti.size(); i++) {
				CarteDTO c = new CarteDTO();
				c.setId(carti.get(i).getId());
				c.setNume(carti.get(i).getNume());
				c.setAnul(carti.get(i).getAnul());
				c.setAutor(carti.get(i).getAutor());
				c.setStatus(carti.get(i).getStatus());
				c.setData_retur(carti.get(i).getData_retur());
				car.add(c);
			}

			return car;
		}
		else if ("Autor".equals(dupa)){
			Query query = em.createNamedQuery("dupaAutor");
			query.setParameter("autor_Param", valoare);
			List<Carte> carti = query.getResultList();
			List<CarteDTO> car = new ArrayList<CarteDTO>();// = new

			for (int i = 0; i < carti.size(); i++) {
				CarteDTO c = new CarteDTO();
				c.setId(carti.get(i).getId());
				c.setNume(carti.get(i).getNume());
				c.setAnul(carti.get(i).getAnul());
				c.setAutor(carti.get(i).getAutor());
				c.setStatus(carti.get(i).getStatus());
				c.setData_retur(carti.get(i).getData_retur());
				car.add(c);
			}

			return car;
		}
		else if ("Status".equals(dupa)){
			Query query = em.createNamedQuery("dupaStatus");
			query.setParameter("status_Param", valoare);
			List<Carte> carti = query.getResultList();
			List<CarteDTO> car = new ArrayList<CarteDTO>();// = new

			for (int i = 0; i < carti.size(); i++) {
				CarteDTO c = new CarteDTO();
				c.setId(carti.get(i).getId());
				c.setNume(carti.get(i).getNume());
				c.setAnul(carti.get(i).getAnul());
				c.setAutor(carti.get(i).getAutor());
				c.setStatus(carti.get(i).getStatus());
				c.setData_retur(carti.get(i).getData_retur());
				car.add(c);
			}

			return car;
		}
		else if ("Anul".equals(dupa)){
			if (dupa.length() != 4)
				return null;
			if (!isNumber(valoare))
				return null;
			int an = Integer.parseInt(valoare);
			List<CarteDTO> car = new ArrayList<CarteDTO>();// = new
			car = findAllBooks();
			for (int i=0; i<car.size(); i++){
				int an1 = Integer.parseInt(car.get(i).getAnul());
				if (an1 < an)
					car.remove(car.get(i));
			}
			return car;
		}
		return null;
	}

}
